package com.naiterui.ehp.bs.cms.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.naiterui.ehp.bp.constants.InquirerRelationEnum;
import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bs.cms.common.vo.PageParamsVO;
import com.naiterui.ehp.bs.cms.common.vo.PageVO;
import com.naiterui.ehp.bs.cms.modules.oms.service.IOrderService;
import com.naiterui.ehp.bs.cms.modules.oms.vo.OrderVO;
import com.naiterui.ehp.bs.cms.modules.recommend.entity.MedicalRecordImgOperatorLog;
import com.naiterui.ehp.bs.cms.modules.recommend.mapper.MedicalRecordImgOperatorLogMapper;
import com.naiterui.ehp.bs.cms.modules.recommend.vo.MedicalRecordImgOperatorLogVO;
import com.naiterui.ehp.bs.cms.modules.user.entity.Patient;
import com.naiterui.ehp.bs.cms.modules.user.feign.EmrFeignClient;
import com.naiterui.ehp.bs.cms.modules.user.mapper.ConsultSessionMapper;
import com.naiterui.ehp.bs.cms.modules.user.mapper.DoctorMapper;
import com.naiterui.ehp.bs.cms.modules.user.mapper.PatientMapper;
import com.naiterui.ehp.bs.cms.modules.user.service.IPatientService;
import com.naiterui.ehp.bs.cms.modules.user.vo.CaseDetailVO;
import com.naiterui.ehp.bs.cms.modules.user.vo.ConsultSessionVO;
import com.naiterui.ehp.bs.cms.modules.user.vo.DoctorBaseInfoVO;
import com.naiterui.ehp.bs.cms.modules.user.vo.PatientBaseInfoVO;
import com.naiterui.ehp.bs.cms.modules.user.vo.PatientDetailsVO;
import com.naiterui.ehp.bs.cms.modules.user.vo.PatientPageVO;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements IPatientService {

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ConsultSessionMapper consultSessionMapper;

    @Autowired
    private MedicalRecordImgOperatorLogMapper medicalRecordImgOperatorLogMapper;

    @Autowired
    private EmrFeignClient emrFeignClient;

    @Override
    public PageVO<PatientPageVO> queryPage(PageParamsVO pageParamsVO, PatientPageVO patientVO) {

        QueryWrapper<PatientPageVO> entityWrapper = buildEntityWrapper(pageParamsVO, patientVO);

        Page<PatientPageVO> page = baseMapper.getPage(pageParamsVO.getPage(), entityWrapper);

        List<PatientPageVO> patientList = page.getRecords();
        if (CollectionUtils.isNotEmpty(patientList)) {
            for (PatientPageVO vo : patientList) {
                vo.setNickName(StringUtils.isEmpty(vo.getNickName()) ? vo.getMiniName() : vo.getNickName());
                vo.setHeadUrl(StringUtils.isEmpty(vo.getHeadUrl()) ? vo.getAvatar() : vo.getHeadUrl());
                vo.setGender(null == vo.getGender() ? vo.getMiniGender() : vo.getGender());
            }
        }

        return PageVO.toPageVo(patientList, page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    public PatientDetailsVO getPatientDetailsVO(Long patientId) {
        PatientDetailsVO patientDetailsVO = new PatientDetailsVO();

        //患者基本信息
        PatientBaseInfoVO patientBaseInfoVO = baseMapper.get(patientId);
        if (patientBaseInfoVO != null) {
            patientBaseInfoVO.setAddress(String.join(",", patientBaseInfoVO.getCityName(), patientBaseInfoVO.getAddress()));
            patientDetailsVO.setBaseInfo(patientBaseInfoVO);
        } else {
            //就诊人中没有本人,只查询基本信息
            patientBaseInfoVO = baseMapper.getPatientBaseInfo(patientId);
            if (patientBaseInfoVO != null) {
                patientBaseInfoVO.setAddress("");
                patientDetailsVO.setBaseInfo(patientBaseInfoVO);
            }
        }

        //患者私人医生
        List<DoctorBaseInfoVO> doctorVOS = doctorMapper.getByPatientId(patientId);
        patientDetailsVO.setFocusOnDoctors(doctorVOS);

        //会话列表
        List<ConsultSessionVO> consultSessionVOList = consultSessionMapper.getByPatient(patientId);
        consultSessionVOList.forEach(s -> s.setInquirerRelationName(InquirerRelationEnum.getNameByValue(s.getInquirerRelation())));
        patientDetailsVO.setConsultSessionList(consultSessionVOList);

        //订单
        List<OrderVO> orderList = orderService.getByPatientId(patientId);
        patientDetailsVO.setOrderList(orderList);

        return patientDetailsVO;
    }

    private QueryWrapper<PatientPageVO> buildEntityWrapper(PageParamsVO pageParamsVO, PatientPageVO patientVO) {
        QueryWrapper<PatientPageVO> entityWrapper = pageParamsVO.getEntityWrapper("t");
        Long id = patientVO.getId();
        entityWrapper.eq(id != null, "t.id", id);
        String name = patientVO.getName();
        entityWrapper.like(StringUtils.isNotBlank(name), "t.name", name);
        String phone = patientVO.getPhone();
        entityWrapper.eq(StringUtils.isNotBlank(phone), "t.phone", phone);
        return entityWrapper;
    }

    @Override
    public void caseDownloadReport(String recordId, Integer type) throws BusinessException {
        String operator = SecurityUtils.getCurrentUser().getUsername();
        MedicalRecordImgOperatorLog log = MedicalRecordImgOperatorLog.builder().operator(operator).recordId(recordId).type(type).build();
        log.setCreatedAt(new Date());
        medicalRecordImgOperatorLogMapper.insert(log);
    }

    @Override
    public CaseDetailVO caseDetail(PageParamsVO pageParamsVO, String recordId) throws BusinessException {
        ResponseVO<String> pdfUrlResponse = emrFeignClient.caseSignPdfUrl(recordId);
        String pdfUrl = pdfUrlResponse.getData();
        QueryWrapper<MedicalRecordImgOperatorLogVO> entityWrapper = pageParamsVO.getEntityWrapper("t");
        entityWrapper.eq(recordId != null, "t.record_id", recordId);
        Page<MedicalRecordImgOperatorLogVO> page = medicalRecordImgOperatorLogMapper.getPage(pageParamsVO.getPage(), entityWrapper);
        CaseDetailVO caseDetail = CaseDetailVO.builder().operatorList(PageVO.toPageVo(page)).pdfUrl(pdfUrl).build();
        return caseDetail;
    }
}
